import { ref, reactive , toRefs } from 'vue';
import { notify } from '@/utils/element';
interface Params {
    initData?: any;     //初始数据,(一般用于新增时的初始数据)
    add?: Function;
    update?: Function;
}
function useForm<T>(params: Params, emit?: any, props?: any) {
    const { initData = {}, add = () => {}, update = () => {} } = params;

    const formRef = ref();

    const state = reactive({
        loading: false,
        visible: false,
        title: '新增',
        type: 'add' as FormType,
        formData: {} as T,
        oldFormData: {} as T,
    });

    function open(type: FormType, title: string, data= {} as any) {
        state.type = type;
        state.title = title;
        //合并初始数据，深度拷贝，不然会影响原数据
        state.formData = JSON.parse(JSON.stringify({ ...initData, ...data }));
        //当修改操作时，做数据校验
        state.oldFormData = Object.assign({}, state.formData);
        state.visible = true;
    }

    function close() {
        if(state.loading) return;
        formRef.value?.resetFields();
        state.visible = false;
    }

    //提交表单
    function submitForm() {
        formRef.value?.validate((valid: boolean) => {
            if(!valid) return;
            //调用接口，提交数据
            submitData();
        });
    }

    async function submitData() {
        try {
            state.loading = true;
            let res;
            if(state.type === 'edit') {
                res = await update(state.formData);
            }else {
                res = await add(state.formData);
            }
            state.loading = false;
            if(res.code !== 200) return;
            notify('操作成功！', {type: 'success'});
            //关闭窗口
            close();
            //触发父组件重新加载数据
            emit('refresh');
        } catch (error) {
        } finally {
            state.loading = false;
        }
    }
    return {
        formRef,
        ...toRefs(state),
        open,
        close,
        submitForm,
    }
};

export default useForm;
export { useForm };
